package com.andy.buyu.server.action;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.andy.buyu.server.dao.DaoUtils;
import com.andy.buyu.server.dao.vo.Where;
import com.andy.buyu.server.entity.UsrGameInfo;
import com.andy.buyu.server.entity.UsrUser;
import com.andy.buyu.server.game.GameConf;
import com.andy.buyu.server.game.GameUser;
import com.andy.buyu.server.game.Global;
import com.andy.buyu.server.socket.GmAction;
import com.andy.buyu.server.socket.MySocketSession;
import com.andy.buyu.server.socket.SendUtil;
import com.andy.buyu.server.socket.codec.DataWrap;
import com.andy.buyu.server.utils.CommonUtils;
import com.andy.buyu.server.utils.ErrorCode;
import com.andy.buyu.server.utils.GoConstant;

/**
 * 登录逻辑
 * @author cuiwm
 *
 */
@Component(GmAction.ACTION_PREFIX+GmAction.ACTION_100)
public class LoginAction implements IReqAction{

	@Override
	public void doAction(MySocketSession session, DataWrap data) {
		String userName = data.getString();
		
		if(StringUtils.isNotBlank(userName)) {
			login(session, userName);
		}else {
			// 测试用
			register(session);
		}
		
	}
	
	public void register(MySocketSession session) {
		UsrUser user = new UsrUser();
		user.setUserName(RandomStringUtils.randomAlphabetic(10));
		user.setNickName("测试玩家");
		user.setIcon(RandomUtils.nextInt(0, 10));
		DaoUtils.insert(user);
		user.setNickName(user.getNickName()+user.getId());
		DaoUtils.update(user);
		
		UsrGameInfo gameInfo = new UsrGameInfo();
		gameInfo.setUid(user.getId());
		gameInfo.addCoin(GameConf.getConfInt("init_coin"));
		gameInfo.setWinCount(0);
		gameInfo.setLoseCount(0);
		DaoUtils.insert(gameInfo);
		
		login(session, user.getUserName());
		
	}
	
	public void login(MySocketSession session,String userName) {
		UsrUser user = null;
		user = DaoUtils.getOne(UsrUser.class, Where.eq("user_name", userName));
		if(user == null){
			SendUtil.sendError(session, ErrorCode.ERROR_1);
		}else{
			checkLogined(user);
			
			GameUser gameUser = new GameUser(user);
			UsrGameInfo gameInfo = DaoUtils.getOne(UsrGameInfo.class, Where.eq("uid", user.getId()));
			gameUser.setGameInfo(gameInfo);
			
			Global.addUser(user.getId(), session);
			session.setAttr(GoConstant.USER_SESSION_KEY, gameUser);
			
			SendUtil.send100(session, gameUser);
			// 大厅信息
			SendUtil.send102(gameUser);
		}
	}

	/**
	 * 检查是否已登录，如果已经登录则踢出去
	 * @param user
	 */
	private void checkLogined(UsrUser user) {
		MySocketSession session = Global.getSession(user.getId());
		if(session != null){
			// 已登录
			CommonUtils.outRoom(session.getUser(),2);
			Global.removeSession(session);
			session.invalidate();
		}
	}

	
	
	
}
